//
//  CommunityInteractionListViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/18.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "InteractionSectionHeaderView.h"
#import "InteractionSectionHeaderView.h"

#import "EvaluateSectionFooterView.h"
#import "MyEvaCell.h"

#import "BA_CommunityInputTextView.h"
#import "ReportReasonViewController.h"

#import "PostDetailViewController.h"
#import "TopicDetailViewController.h"
#import "QADetailViewController.h"

#import "CommunityInteractionListViewController.h"

@interface CommunityInteractionListViewController ()<UITableViewDelegate, UITableViewDataSource, BA_BottomInputViewDelegate, UITextViewDelegate>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, strong) NSMutableArray <CommunityInteractionModel *>*dataArray;

@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) BA_CommunityInputTextView *footView;


@end

@implementation CommunityInteractionListViewController

- (instancetype)initWithType:(CommunityInteractionListType)type {
    
    self = [super init];
    
    if (self) {
        self.type = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UIWindow * keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self.footView];
    [self.footView hideView];
    
    [self refreshParam];
    [self request_evaList];
    [self initView];
}

- (void)refreshParam {
    self.pageSize = 10;
    self.pageNum = 1;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
    [[IQKeyboardManager sharedManager] setEnable:NO];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    [[IQKeyboardManager sharedManager] setEnable:YES];

    [self.footView hideView];
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    [self.footView hideView];
}

-(BOOL)textViewShouldEndEditing:(UITextView *)textView {
    
    [self.footView hideView];
    return YES;
}

-(void)BA_BottomInputViewSendTextMessage:(NSString *)message {
    
    [self request_postEvaWithIndex:self.selectIndex AndContent:message];
}

- (void)initView {
    
    self.title = @"我的评论";
    
    [self.view addSubview:self.tableview];
    
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [self.tableview reloadData];
}

- (void)showMoreActionWithIndex:(NSInteger)index {
    
    WEAKSELF
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *liveAction = [UIAlertAction actionWithTitle:@"举报"
                                             style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction *action) {
        ReportReasonViewController *vc = [[ReportReasonViewController alloc] init];
        
        CommunityInteractionModel *model = self.dataArray[index];
        vc.level = model.level;
        
        //类型（1：谈婚，2：论嫁，3：问答）必传
        switch (model.type) {
            case 1:{
                if ([model.level isEqualToString:@"1"]) {
                    vc.baseId = model.pid;
                    vc.type = BAReportType_post;
                } else if ([model.level isEqualToString:@"2"]) {
                    vc.baseId = model.cpId;
                    vc.type = BAReportType_postEva;
                } else if ([model.level isEqualToString:@"3"]) {
                    vc.baseId = model.cspId;
                    vc.type = BAReportType_PostEvaReply;
                } else {
                    vc.baseId = model.cspnId;
                    vc.type = BAReportType_PostEvaReply;
                }
                
            } break;
            case 2:{
                
                if ([model.level isEqualToString:@"1"]) {
                    vc.type = BAReportType_topic;
                    vc.baseId = model.pid;

                } else if ([model.level isEqualToString:@"2"]) {
                    vc.type = BAReportType_topcEva;
                    vc.baseId = model.cpId;

                } else if ([model.level isEqualToString:@"3"]) {
                    vc.baseId = model.cspId;
                    vc.type = BAReportType_topicEvaReply;
                } else {
                    vc.baseId = model.cspnId;
                    vc.type = BAReportType_topicEvaReply;
                }
                
            } break;
            case 3:{
//                if ([model.level isEqualToString:@"2"]) {
//                    vc.type = BAReportType_qa;
//                    vc.baseId = model.pid;
//
//                } else {
                    vc.type = BAReportType_qaAnswer;
                    vc.baseId = model.cpId;
//                }
                
            } break;
            default:
                break;
        }
        
        
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
    }];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消"
                                           style:UIAlertActionStyleCancel
                                         handler:^(UIAlertAction *action) {

    }];
    
    [alertController addAction:liveAction];
    [alertController addAction:cancleAction];
    [alertController setModalPresentationStyle:UIModalPresentationPopover];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    switch (self.type) {
        case CommunityInteractionListType_eva:{
            return [InteractionSectionHeaderView calculateHWithModel:self.dataArray[section]];
        } break;
        case CommunityInteractionListType_thumb:{
            return 60;
        } break;
        default:
            break;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([self.dataArray[indexPath.section].level isEqualToString:@"3"] || [self.dataArray[indexPath.section].level isEqualToString:@"4"]) {
        return 60;
    }
    return 30;

}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    InteractionSectionHeaderView *sectionHeader = [[NSBundle mainBundle] loadNibNamed:@"InteractionSectionHeaderView" owner:nil options:nil].firstObject;
    
    [sectionHeader fillWithModel:self.dataArray[section] type:self.type];
    
    WEAKSELF
    sectionHeader.InteractionSectionHeaderViewBlock = ^{
      
        //点击了三个点需要的操作   //举报
        [weakSelf showMoreActionWithIndex:section];
        
    };
    
    return sectionHeader;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    EvaluateSectionFooterView*sectionFooter = [[NSBundle mainBundle] loadNibNamed:@"EvaluateSectionFooterView" owner:nil options:nil].firstObject;
    
    WEAKSELF
    switch (self.type) {
        case CommunityInteractionListType_eva:{
            [sectionFooter fillWithModel:self.dataArray[section] type:EvaluateSectionFooter_reply];
            
            sectionFooter.EvaluateSectionFooterViewBlock = ^{
                
                weakSelf.selectIndex = section;
                [weakSelf.footView showView];
                [weakSelf.footView.textView becomeFirstResponder];
                
            };
        } break;
        case CommunityInteractionListType_thumb:{
            [sectionFooter fillWithModel:self.dataArray[section] type:EvaluateSectionFooter_thumb];

        } break;
        default:
            break;
    }
    
    return sectionFooter;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MyEvaCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyEvaCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillWithModel:self.dataArray[indexPath.section]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    //类型（1：谈婚，2：论嫁，3：问答）必传
    switch (self.dataArray[indexPath.section].type) {
        case 1:{
            
            PostDetailViewController *vc = [[PostDetailViewController alloc] init];
            vc.pid = self.dataArray[indexPath.section].pid;
            [self.navigationController pushViewController:vc animated:YES];
        } break;
        case 2:{
            
            TopicDetailViewController *vc = [[TopicDetailViewController alloc] init];
            vc.pid = self.dataArray[indexPath.section].pid;
            [self.navigationController pushViewController:vc animated:YES];
        } break;
        case 3:{
            
            QADetailViewController *vc = [[QADetailViewController alloc] init];
            vc.mqId = self.dataArray[indexPath.section].pid;
            [self.navigationController pushViewController:vc animated:YES];
            
        } break;
        default:
            break;
    }
    
}

- (BA_CommunityInputTextView *)footView {
    if (_footView == nil) {
        _footView = [[BA_CommunityInputTextView alloc]init];
        _footView.delegate = self;
        _footView.textView.delegate = self;
    }
    return _footView;
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
                
        [_tableview registerNib:[UINib nibWithNibName:@"MyEvaCell" bundle:nil] forCellReuseIdentifier:@"MyEvaCellID"];

        [self.view addSubview:_tableview];
        
        [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.bottom.mas_equalTo(0);
        }];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_evaList];
        }];

        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_evaList];
        }];
        
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;

    }
    return _tableview;
}


- (void)request_evaList {
        
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSMutableDictionary *t = @{}.mutableCopy;

    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    [t setValue:@"2" forKey:@"isDel"];
//    [t setValue:@"2" forKey:@"type"];
    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    
    switch (self.type) {
        case CommunityInteractionListType_eva:{
            [t setValue:@"1" forKey:@"mold"];
        } break;
        case CommunityInteractionListType_thumb:{
            [t setValue:@"2" forKey:@"mold"];
        } break;
        default:
            break;
    }
    
    [t setValue:[TTUserModel sharedObject].userId forKey:@"userId"];

    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MyCommunityHD];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        [SVProgressHUD dismiss];

        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    NSArray *list = [resultDic valueForKey:@"list"];
                    
                    if ([list isKindOfClass:[NSArray class]]) {
                    
                        if (weakSelf.pageNum == 1) {
                            self.dataArray = @[].mutableCopy;
                            
                            if (list.count == 0) {
                                [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_NoHD btnTitle:@"" didPressButton:^{
                                }];
                            }
                        }
                        
                        for (NSDictionary *dic in list) {
                            
                            CommunityInteractionModel *model = [CommunityInteractionModel modelWithDictionary:dic];
                            [weakSelf.dataArray addObject:model];
                        }
                        
                        [weakSelf.tableview reloadData];
                    }
                }
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
}


- (void)request_postEvaWithIndex:(NSInteger)index AndContent:(NSString *)content {
        
    CommunityInteractionModel *model = self.dataArray[index];
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:content forKey:@"content"];

    //类型（1：谈婚，2：论嫁，3：问答）必传
//    [dic setValue:model.pid forKey:@"baseId"];
    
    NSInteger level = model.level.integerValue;
    
    if (level<4) {
        level++;
    }
    [dic setValue:@(level) forKey:@"level"];
    
    if (level==3) {
        [dic setValue:model.cpId forKey:@"baseId"];
    }
    
    if (level==4) {
        [dic setValue:model.cspId forKey:@"baseId"];
        [dic setValue:model.cspnId forKey:@"cspnId"];
    }
    
    [dic setValue:model.replySource forKey:@"source"];
    [dic setValue:model.replyUserId forKey:@"userId"];
    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    [dic setValue:@"1" forKey:@"mold"];

    //类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@(model.type) forKey:@"type"];
    //层级（1,2,3）必传
    [dic setValue:@"2" forKey:@"replySource"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在发布评论"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                weakSelf.footView.textView.text = @"";
                [weakSelf.view endEditing:YES];
                
                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

@end
